<template>
  <div class="trading-container">
    <!-- 顶部工具栏 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <el-button
          type="default"
          @click="navigateToHome"
          :icon="ArrowLeft"
          size="small"
        >
          返回首页
        </el-button>
        <el-button
          type="primary"
          @click="navigateToMultiGrid"
          :icon="Grid"
          size="small"
        >
          多网格视图
        </el-button>
        <span class="page-title">交易级监控视图</span>
      </div>

      <div class="toolbar-right">
        <el-switch
          v-model="isRealtime"
          active-text="实时"
          inactive-text="暂停"
          @change="handleRealtimeToggle"
        />
        <el-button
          type="primary"
          size="small"
          @click="refreshData"
          :icon="Refresh"
        >
          刷新
        </el-button>
      </div>
    </div>

    <!-- 主图表区域 -->
    <div class="main-chart-container">
      <div class="chart-header">
        <div class="chart-title">综合监控面板</div>
        <div class="chart-controls">
          <el-select
            v-model="selectedTimeRange"
            placeholder="时间范围"
            size="small"
            style="width: 120px"
          >
            <el-option label="1分钟" value="1m" />
            <el-option label="5分钟" value="5m" />
            <el-option label="15分钟" value="15m" />
            <el-option label="1小时" value="1h" />
          </el-select>
        </div>
      </div>

      <div
        ref="mainChartRef"
        class="main-chart"
        :style="{ height: mainChartHeight + 'px' }"
      ></div>
    </div>

    <!-- 下方小图表区域 -->
    <div class="sub-chart-container">
      <div class="sub-chart-header">
        <div class="sub-chart-title">通道详情</div>
        <div class="sub-chart-controls">
          <el-select
            v-model="selectedSubChannel"
            placeholder="选择通道"
            size="small"
            style="width: 150px"
            @change="handleSubChannelChange"
          >
            <el-option
              v-for="channel in availableChannels"
              :key="channel.name"
              :label="channel.name"
              :value="channel.name"
            />
          </el-select>

          <el-select
            v-model="subChartType"
            placeholder="图表类型"
            size="small"
            style="width: 100px; margin-left: 10px"
            @change="handleSubChartTypeChange"
          >
            <el-option label="折线图" value="line" />
            <el-option label="柱状图" value="bar" />
            <el-option label="面积图" value="area" />
          </el-select>
        </div>
      </div>

      <div
        ref="subChartRef"
        class="sub-chart"
        :style="{ height: subChartHeight + 'px' }"
      ></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, nextTick, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ArrowLeft, Refresh, Grid } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { useWebSocket } from '@/composables/useWebSocket'
import type { RealtimeData, Channel } from '@/types/chart'

// 路由
const router = useRouter()

// WebSocket数据
const { isConnected, chartData, connectWebSockets, disconnectWebSockets } = useWebSocket()

// 图表引用
const mainChartRef = ref<HTMLElement>()
const subChartRef = ref<HTMLElement>()
let mainChart: echarts.ECharts | null = null
let subChart: echarts.ECharts | null = null

// 响应式状态
const isRealtime = ref(true)
const selectedTimeRange = ref('5m')
const selectedSubChannel = ref('拉出值')
const subChartType = ref('line')

// 计算图表高度
const containerHeight = computed(() => window.innerHeight - 100) // 减去工具栏高度
const mainChartHeight = computed(() => Math.floor(containerHeight.value * 0.65)) // 65%
const subChartHeight = computed(() => Math.floor(containerHeight.value * 0.3))  // 30%

// 可用通道配置
const availableChannels = ref<Channel[]>([
  { name: '拉出值', unit: 'mm', min: -600, max: 600, color: '#91CC75', selected: true, type: 'line' },
  { name: '导高', unit: 'mm', min: 5000, max: 6600, color: '#5470C6', selected: true, type: 'line' },
  { name: '磨耗表', unit: 'mm', min: 0, max: 20, color: '#8B5CF6', selected: true, type: 'line' },
  { name: '速度', unit: 'km/h', min: 0, max: 200, color: '#EE6666', selected: false, type: 'line' },
  { name: '网压', unit: 'kV', min: 25, max: 30, color: '#FC8452', selected: false, type: 'line' },
  { name: '接触力', unit: 'N', min: 0, max: 300, color: '#73C0DE', selected: false, type: 'line' },
  { name: '加速度', unit: 'm/s²', min: 0, max: 50, color: '#3BA272', selected: false, type: 'line' }
])

// 导航函数
const navigateToHome = () => {
  router.push('/')
}

const navigateToMultiGrid = () => {
  router.push('/')
}

// 实时开关处理
const handleRealtimeToggle = (value: boolean) => {
  console.log('实时模式:', value)
  // 这里可以添加暂停/恢复数据更新的逻辑
}

// 刷新数据
const refreshData = () => {
  console.log('刷新数据')
  updateMainChart()
  updateSubChart()
}

// 子图表通道切换
const handleSubChannelChange = (channelName: string) => {
  console.log('切换子图表通道:', channelName)
  updateSubChart()
}

// 子图表类型切换
const handleSubChartTypeChange = (type: string) => {
  console.log('切换子图表类型:', type)
  updateSubChart()
}

// 初始化主图表
const initMainChart = () => {
  if (!mainChartRef.value) return

  mainChart = echarts.init(mainChartRef.value)

  const option = {
    title: {
      text: '多通道综合监控',
      left: 'center',
      textStyle: { fontSize: 16, fontWeight: 'bold' }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'cross' }
    },
    legend: {
      data: ['拉出值', '导高', '磨耗表', '速度', '网压'],
      top: '8%'
    },
    grid: {
      left: '8%',
      right: '8%',
      top: '15%',
      bottom: '10%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: chartData.value.X,
      axisLabel: { fontSize: 10 }
    },
    yAxis: [
      {
        type: 'value',
        name: '拉出值/导高/磨耗 (mm)',
        position: 'left',
        axisLabel: { formatter: '{value}' },
        splitLine: { show: true, lineStyle: { type: 'dashed', opacity: 0.3 } }
      },
      {
        type: 'value',
        name: '速度/网压 (km/h|kV)',
        position: 'right',
        axisLabel: { formatter: '{value}' },
        splitLine: { show: false }
      }
    ],
    series: [
      {
        name: '拉出值',
        type: 'line',
        yAxisIndex: 0,
        data: chartData.value.X1,
        lineStyle: { color: '#91CC75', width: 1.5 },
        showSymbol: false,
        connectNulls: false
      },
      {
        name: '导高',
        type: 'line',
        yAxisIndex: 0,
        data: chartData.value.Y1,
        lineStyle: { color: '#5470C6', width: 1.5 },
        showSymbol: false,
        connectNulls: false
      },
      {
        name: '磨耗表',
        type: 'line',
        yAxisIndex: 0,
        data: chartData.value.MoHaoList1,
        lineStyle: { color: '#8B5CF6', width: 1.5 },
        showSymbol: false,
        connectNulls: false
      },
      {
        name: '速度',
        type: 'line',
        yAxisIndex: 1,
        data: chartData.value.SpeedList,
        lineStyle: { color: '#EE6666', width: 1.5 },
        showSymbol: false,
        connectNulls: false
      },
      {
        name: '网压',
        type: 'line',
        yAxisIndex: 1,
        data: chartData.value.fVot,
        lineStyle: { color: '#FC8452', width: 1.5 },
        showSymbol: false,
        connectNulls: false
      }
    ],
    animation: false,
    backgroundColor: '#fafafa'
  }

  mainChart.setOption(option)
}

// 初始化子图表
const initSubChart = () => {
  if (!subChartRef.value) return

  subChart = echarts.init(subChartRef.value)
  updateSubChart()
}

// 更新主图表
const updateMainChart = () => {
  if (!mainChart) return

  const option = {
    xAxis: {
      data: chartData.value.X
    },
    series: [
      { data: chartData.value.X1 },
      { data: chartData.value.Y1 },
      { data: chartData.value.MoHaoList1 },
      { data: chartData.value.SpeedList },
      { data: chartData.value.fVot }
    ]
  }

  mainChart.setOption(option)
}

// 更新子图表
const updateSubChart = () => {
  if (!subChart) return

  const selectedChannel = availableChannels.value.find(ch => ch.name === selectedSubChannel.value)
  if (!selectedChannel) return

  // 获取对应的数据
  let data: (number | null)[] = []
  switch (selectedSubChannel.value) {
    case '拉出值':
      data = chartData.value.X1
      break
    case '导高':
      data = chartData.value.Y1
      break
    case '磨耗表':
      data = chartData.value.MoHaoList1
      break
    case '速度':
      data = chartData.value.SpeedList
      break
    case '网压':
      data = chartData.value.fVot
      break
    case '接触力':
      data = chartData.value.fPressList1 || []
      break
    case '加速度':
      data = chartData.value.fVibrationList1 || []
      break
    default:
      data = []
  }

  const option = {
    title: {
      text: `${selectedChannel.name} 详细视图`,
      left: 'center',
      textStyle: { fontSize: 14 }
    },
    tooltip: {
      trigger: 'axis',
      formatter: `{b}<br/>{a}: {c} ${selectedChannel.unit}`
    },
    grid: {
      left: '10%',
      right: '10%',
      top: '20%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: chartData.value.X,
      axisLabel: { fontSize: 9 }
    },
    yAxis: {
      type: 'value',
      name: `${selectedChannel.name} (${selectedChannel.unit})`,
      min: selectedChannel.min,
      max: selectedChannel.max,
      axisLabel: { formatter: `{value}${selectedChannel.unit}` }
    },
    series: [{
      name: selectedChannel.name,
      type: subChartType.value === 'area' ? 'line' : subChartType.value,
      data: data,
      lineStyle: { color: selectedChannel.color, width: 2 },
      itemStyle: { color: selectedChannel.color },
      areaStyle: subChartType.value === 'area' ? {
        color: {
          type: 'linear',
          x: 0, y: 0, x2: 0, y2: 1,
          colorStops: [
            { offset: 0, color: selectedChannel.color },
            { offset: 1, color: selectedChannel.color + '20' }
          ]
        }
      } : undefined,
      showSymbol: false,
      connectNulls: false
    }],
    animation: false,
    backgroundColor: '#ffffff'
  }

  subChart.setOption(option)
}

// 监听数据变化
watch(() => chartData.value, () => {
  if (isRealtime.value) {
    updateMainChart()
    updateSubChart()
  }
}, { deep: true })

// 窗口大小调整
const handleResize = () => {
  nextTick(() => {
    mainChart?.resize()
    subChart?.resize()
  })
}

// 生命周期
onMounted(() => {
  // 连接WebSocket
  connectWebSockets()

  // 初始化图表
  nextTick(() => {
    initMainChart()
    initSubChart()
  })

  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  // 清理图表
  if (mainChart) {
    mainChart.dispose()
    mainChart = null
  }
  if (subChart) {
    subChart.dispose()
    subChart = null
  }

  // 移除事件监听
  window.removeEventListener('resize', handleResize)

  // 断开WebSocket连接
  disconnectWebSockets()
})
</script>

<style scoped>
.trading-container {
  width: 100vw;
  height: 100vh;
  background: linear-gradient(to bottom, #f8f9fa, #e9ecef);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.toolbar {
  height: 50px;
  background: #ffffff;
  border-bottom: 1px solid #dee2e6;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.toolbar-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.page-title {
  font-size: 16px;
  font-weight: 600;
  color: #495057;
}

.toolbar-right {
  display: flex;
  align-items: center;
  gap: 15px;
}

.main-chart-container {
  flex: 1;
  margin: 10px;
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  overflow: hidden;
}

.chart-header {
  height: 40px;
  background: #f8f9fa;
  border-bottom: 1px solid #dee2e6;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 15px;
}

.chart-title {
  font-size: 14px;
  font-weight: 600;
  color: #495057;
}

.chart-controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

.main-chart {
  width: 100%;
  background: #fafafa;
}

.sub-chart-container {
  height: auto;
  margin: 0 10px 10px 10px;
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  overflow: hidden;
}

.sub-chart-header {
  height: 40px;
  background: #f8f9fa;
  border-bottom: 1px solid #dee2e6;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 15px;
}

.sub-chart-title {
  font-size: 14px;
  font-weight: 600;
  color: #495057;
}

.sub-chart-controls {
  display: flex;
  align-items: center;
}

.sub-chart {
  width: 100%;
  background: #ffffff;
}

/* 深色模式样式 */
@media (prefers-color-scheme: dark) {
  .trading-container {
    background: linear-gradient(to bottom, #2d3748, #1a202c);
  }

  .toolbar {
    background: #2d3748;
    border-bottom-color: #4a5568;
  }

  .page-title {
    color: #e2e8f0;
  }

  .main-chart-container,
  .sub-chart-container {
    background: #2d3748;
  }

  .chart-header,
  .sub-chart-header {
    background: #4a5568;
    border-bottom-color: #718096;
  }

  .chart-title,
  .sub-chart-title {
    color: #e2e8f0;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .toolbar {
    flex-direction: column;
    height: auto;
    padding: 10px;
  }

  .toolbar-left,
  .toolbar-right {
    width: 100%;
    justify-content: space-between;
  }

  .chart-header,
  .sub-chart-header {
    flex-direction: column;
    height: auto;
    padding: 10px 15px;
  }

  .chart-controls,
  .sub-chart-controls {
    margin-top: 10px;
  }
}
</style>